package com.shop.framework.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import com.shop.framework.service.FileService;
import com.shop.framework.vo.FileItem;


@Component
public class FileUtil {
    private static final String PUB_DIRECTORY = "/Users/Geryon/Workspace/Java/ooa-shop-admin/WebContent/pub/";

    private static FileService service;

    @Autowired(required=true)
    private FileUtil(FileService fileService) {
        if (service == null) {
            FileUtil.service = fileService;
        }
    }

    public static String getPubDirectory() {
        return PUB_DIRECTORY;
    }

    public static void saveFile(String fileId, String fileName, byte[] fileBytes) throws IOException {
        service.saveFile(fileId, fileName, fileBytes);
        FileCopyUtils.copy(fileBytes, new File(getPubDirectory() + fileId));
        //FileCopyUtils.copy(fileBytes, new File(getPubDirectory() + fileName));
    }

    public static void deleteFile(String fileId) throws IOException {
        service.deleteFile(fileId);
        new File(getPubDirectory() + fileId).delete();
    }

    public static FileItem touchAndGetFile(String fileId) throws IOException {
        File file = new File(getPubDirectory() + fileId);

        if (file.exists()) {
            file.setLastModified(new Date().getTime());
            service.touchFile(fileId);
        } else {
            FileItem fileItem = service.getFile(fileId);

            FileCopyUtils.copy(fileItem.getAnex_fil_txt(), file);
        }

        FileItem fileItem = service.getFileInfo(fileId);

        return fileItem;
    }

    public static void increaseRefCount(String fileId) throws IOException {
        service.increaseRefCount(fileId);
    }

    public static void decreaseRefCount(String fileId) throws IOException {
        if (service.decreaseRefCount(fileId) <= 0) {
            deleteFile(fileId);
        }
    }

    public static File openFile(String fileId) throws IOException {
        touchAndGetFile(fileId);

        return new File(getPubDirectory() + fileId);
    }
}
